package com.itheima.sh.controller;

import com.itheima.sh.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;


    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod="queryByIdFallback")
    public User queryById(@PathVariable("id") String username){

        // 硬编码
//        String url = "http://localhost:8081/user/"+username;

        // 根据服务名从Eureka server中获取当前服务的实例
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+username;

        // Ribbon 地址调用是 IP和port 替换成 服务名称
        String url = "http://user-service/user/"+username;

        System.out.println("我是Master");

        if ("itheima".equals(username)) {
            throw new RuntimeException("itheima");
        }


        User userMap = restTemplate.getForObject(url, User.class);
        System.out.println(userMap);

        return userMap;
    }

    public User queryByIdFallback(String username) {
        User user = new User();
        user.setName(username);
        user.setUsername("暂停服务");

        return user;
    }

}
